﻿using AutoMapper;
using AutoMapper.Configuration;
using System.Collections.Generic;

namespace Angle.Krill.Utils
{
    internal class AutoMapperHelper
    {
        #region 实体映射
        /// <summary>
        /// 1、类型映射_默认字段一一对应
        /// </summary>
        /// <typeparam name="TSource">源类型</typeparam>
        /// <typeparam name="TDestination">目标类型</typeparam>
        /// <param name="tSource">源数据</param>
        /// <returns></returns>
        public static TDestination AutoMapperTo<TSource, TDestination>(TSource tSource) where TSource : class where TDestination : class
        {
            if (tSource == null) return default;

            var config = new MapperConfiguration(cfg => cfg.CreateMap<TSource, TDestination>());

            var mapper = config.CreateMapper();
            return mapper.Map<TDestination>(tSource);
        }

        /// <summary>
        /// 2、类型映射
        /// ① 字段名称不对应
        /// ② 类型转化
        /// ③ 字段省略
        /// ④ 字段名称或类型不对应
        /// ⑤ 条件赋值或null处理
        /// ⑥ 组合赋值
        /// </summary>
        /// <typeparam name="TSource">源类型</typeparam>
        /// <typeparam name="TDestination">目标类型</typeparam>
        /// <param name="tSource">源数据</param>
        /// <param name="configurationExpression">类型</param>
        /// <returns></returns>
        public static TDestination AutoMapperTo<TSource, TDestination>(TSource tSource, MapperConfigurationExpression configurationExpression) where TSource : class where TDestination : class
        {
            if (tSource == null) return default;
            var config = new MapperConfiguration(configurationExpression);  // 可以自己随意组合赋值

            var mapper = config.CreateMapper();
            return mapper.Map<TDestination>(tSource);
        }
        #endregion 实体映射

        #region 列表映射
        /// <summary>
        /// 3、集合列表类型映射,默认字段名字一一对应
        /// </summary>
        /// <typeparam name="TSource">源类型</typeparam>
        /// <typeparam name="TDestination">目标类型</typeparam>
        /// <param name="source">源数据</param>
        /// <returns></returns>
        public static List<TDestination> AutoMapperToList<TSource, TDestination>(List<TSource> sources) where TSource : class where TDestination : class
        {
            if (sources == null) return new List<TDestination>();

            var config = new MapperConfiguration(cfg => cfg.CreateMap<TSource, TDestination>());

            var mapper = config.CreateMapper();
            return mapper.Map<List<TDestination>>(sources);
        }
        #endregion 列表映射
    }
}
